package com.leyou.item.web;

import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/brand")
public class BrandController {

    @Autowired
    private BrandService brandService;

    /**
     *
     * @param key       搜索关键字
     * @param page      当前页
     * @param rows      页大小
     * @param sortBy    排序的字段名
     * @param desc      是否降序
     * @return          返回自定义的分页结果对象BrandDTO
     */
    @GetMapping("/page")
    public ResponseEntity<PageResult<BrandDTO>> queryBrandPage(
            @RequestParam(value = "key",required = false) String key,
            @RequestParam(value = "page",defaultValue = "1") Integer page,
            @RequestParam(value = "rows",defaultValue = "5") Integer rows,
            @RequestParam(value = "sortBy",defaultValue = "id") String sortBy,
            @RequestParam(value = "desc",defaultValue = "false") Boolean desc
    ){
        PageResult<BrandDTO> result = brandService.queryBrandPage(key,page,rows,sortBy,desc);
        return ResponseEntity.ok(result);
    }

    /**
     *  保存品牌信息: 并维护分类和品牌中间表
     * @param brand 品牌DTO
     * @param cids  分类的id集合
     * @return  无
     */
    @PostMapping
    public ResponseEntity<Void> saveBrand(
            BrandDTO brand,
            @RequestParam("cids")List<Long> cids
    ){
        brandService.saveBrand(brand,cids);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 根据分类id查询品牌列表(通过tb_category_brand中间表进行查询, 自定义多表联查sql语句查询)
     * @param id
     * @return
     */
    @GetMapping("/of/category")
    public ResponseEntity<List<BrandDTO>> queryBrandListByCategoryId(
            @RequestParam("id") Long id
    ){
        return ResponseEntity.ok(brandService.queryBrandListByCategoryId(id));
    }

    /**
     * 通过品牌的id查询品牌查询
     * @param id    品牌id
     * @return      品牌详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<BrandDTO> queryBrandById(
            @PathVariable("id") Long id
    ){
        BrandDTO brandDTO = brandService.queryBrandById(id);
        return ResponseEntity.ok(brandDTO);
    }


    /**
     *  批量查询品牌DTO
     * @param brandIds  品牌id集合
     * @return
     */
    @GetMapping("/list")
    public ResponseEntity<List<BrandDTO>> queryBrandByIds(@RequestParam("ids") List<Long> brandIds){
        return ResponseEntity.ok(brandService.queryBrandByIds(brandIds));
    }

}
